#!/usr/bin/env ruby
#-*- coding:utf-8 -*-

require "net/imap"
require "base64"
require "nokogiri"

if caller.length == 0 then
  cli = Net::IMAP.new 'imap.ym.163.com'
  cli.login 'user', 'pswd'

  mail_boxes = cli.list "", "*"

  # 垃圾邮件
  mail_boxes.each do |box|
    cli.select box.name

    mails = cli.search ['ALL']

    mails.each do |msg_id|
      msg = cli.fetch(msg_id, "(ENVELOPE BODY[TEXT])")[0]
      envelope = msg.attr['ENVELOPE']
      from_server = envelope.from[0]

      # Is not from weibo
      if from_server.mailbox != "noreply" || from_server.host != "service.weibo.com" then
        next
      end

      subject = envelope.subject[2..-3].split("?")
      subject = Base64.decode64(subject[-1].encode("UTF-8", subject[0]))

      if !subject.include? "weibo.com" then
        next
      end

      body = msg.attr['BODY[TEXT]']
      html = Nokogiri::HTML.parse body
      links = html.xpath "//body//table//td/a"
      if links.length == 0 then
        next
      end

      link = links[0].attributes['href'].value
      if link.length == 0 || !link.start_with?("http://weibo.com/signup") then
        next
      end
      puts link
    end

  end

end
